package arpc

import (
	"time"

	red "github.com/zeromicro/go-zero/core/stores/redis"
)

type RedisLock struct {
	lock   *red.RedisLock
	expire int
}

func NewRedisLock(rds *Redis, key string, seconds int) *RedisLock {
	rl := red.NewRedisLock(rds, key)
	if seconds > 0 {
		rl.SetExpire(seconds)
	}

	return &RedisLock{lock: rl, expire: seconds}
}

func (rl *RedisLock) Acquire() (bool, error) {
	return rl.lock.Acquire()
}

func (rl *RedisLock) BlockAcquire() (bool, error) {
	for {
		b, err := rl.lock.Acquire()
		if err != nil {
			return false, err
		}

		if b {
			return b, nil
		}

		time.Sleep(50 * time.Millisecond)
	}
}

func (rl *RedisLock) Release() (bool, error) {
	return rl.lock.Release()
}
